package org.dragonnova.business.common.interceptor;

import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import com.alibaba.fastjson.JSON;

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

	@Override
	public Collection<String> getAttributeNames() {
		return super.getAttributeNames();
	}

	@Override
	public boolean beforeHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
			request.getHeaders().set("Sec-WebSocket-Extensions",
					"permessage-deflate");
		}
		ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
		Map<String, String[]> parameters = serverRequest.getServletRequest()
				.getParameterMap();
		HttpSession session = serverRequest.getServletRequest().getSession(
				isCreateSession());
		attributes.put("parameters", JSON.toJSONString(parameters));
		attributes.put("parameters1", parameters);
		attributes.put("httpsession", session);
		return super.beforeHandshake(request, response, wsHandler, attributes);
	}

	@Override
	public void afterHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception ex) {

		super.afterHandshake(request, response, wsHandler, ex);
	}

}
